package com.haiyou.common.aspect;

import com.github.pagehelper.PageHelper;
import com.haiyou.common.util.RequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.ServletRequestUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 分页切面
 */
@Aspect
@Component
@Slf4j
public class PageHelperAspect {

    @Pointcut("@annotation(com.haiyou.common.anno.PageHelp)")
    public void pointCut() {

    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        log.info("PageHelperAspect代理类开始............");
        //默认第一页
        int pageNum = 1;
        //默认每页10条
        int pageSize = 10;
        try {
            HttpServletRequest request = RequestUtils.getRequest();
            pageNum = ServletRequestUtils.getIntParameter(request, "pageNum", pageNum);
            pageSize = ServletRequestUtils.getIntParameter(request, "pageSize", pageSize);
        } catch (Exception e) {
            log.info("HttpServletRequest ", e.getMessage(), e);
        }
        PageHelper.startPage(pageNum, pageSize, true, false, false);
        Object obj = proceedingJoinPoint.proceed();
        log.info("PageHelperAspect代理类结束，clearPage before:{}", obj);
        PageHelper.clearPage();
        log.info("PageHelperAspect代理类结束，返回值Object:{}", obj);
        return obj;
    }
}
